import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * 任务类型定义
 */
export interface Task {
  id: number
  name: string
  description?: string
  taskType: 'DATA_SYNC' | 'DATA_EXPORT' | 'DATA_IMPORT' | 'REPORT_GENERATE'
  status: 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'PAUSED'
  scheduleType: 'MANUAL' | 'HOURLY' | 'DAILY' | 'WEEKLY' | 'MONTHLY'
  scheduleConfig: string
  dataSourceId?: number
  mappingRuleId?: number
  hospitalId: number
  createdBy: number
  startTime?: string
  endTime?: string
  createTime: string
  updateTime: string
}

/**
 * 任务查询参数
 */
export interface TaskSearchParams extends PageParams {
  name?: string
  taskType?: 'DATA_SYNC' | 'DATA_EXPORT' | 'DATA_IMPORT' | 'REPORT_GENERATE'
  status?: 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'PAUSED'
  hospitalId?: number
  createdBy?: number
}

/**
 * 任务执行参数
 */
export interface TaskExecuteParams {
  force?: boolean
  params?: Record<string, any>
}

/**
 * 获取任务列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchTasks = async (params: TaskSearchParams): Promise<PageResult<Task>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<Task>>>('/api/tasks', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取任务列表失败')
    throw error
  }
}

/**
 * 获取任务详情
 * @param id 任务ID
 * @returns 任务详情
 */
export const getTask = async (id: number): Promise<Task> => {
  try {
    const { data } = await request.get<BaseResponse<Task>>(`/api/tasks/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取任务详情失败')
    throw error
  }
}

/**
 * 创建任务
 * @param data 任务数据
 * @returns 创建的任务信息
 */
export const createTask = async (data: Omit<Task, 'id'>): Promise<Task> => {
  try {
    const { data: response } = await request.post<BaseResponse<Task>>('/api/tasks', data)
    ElMessage.success('创建任务成功')
    return response.data
  } catch (error) {
    ElMessage.error('创建任务失败')
    throw error
  }
}

/**
 * 更新任务
 * @param data 任务数据
 * @returns 更新后的任务信息
 */
export const updateTask = async (data: Task): Promise<Task> => {
  try {
    const { data: response } = await request.put<BaseResponse<Task>>(`/api/tasks/${data.id}`, data)
    ElMessage.success('更新任务成功')
    return response.data
  } catch (error) {
    ElMessage.error('更新任务失败')
    throw error
  }
}

/**
 * 删除任务
 * @param id 任务ID
 */
export const deleteTask = async (id: number): Promise<void> => {
  try {
    await request.delete(`/api/tasks/${id}`)
    ElMessage.success('删除任务成功')
  } catch (error) {
    ElMessage.error('删除任务失败')
    throw error
  }
}

/**
 * 执行任务
 * @param id 任务ID
 * @param params 执行参数
 */
export const executeTask = async (id: number, params?: TaskExecuteParams): Promise<void> => {
  try {
    await request.post(`/api/tasks/${id}/execute`, params)
    ElMessage.success('任务已开始执行')
  } catch (error) {
    ElMessage.error('任务执行失败')
    throw error
  }
}

/**
 * 暂停任务
 * @param id 任务ID
 */
export const pauseTask = async (id: number): Promise<void> => {
  try {
    await request.patch(`/api/tasks/${id}/pause`)
    ElMessage.success('任务已暂停')
  } catch (error) {
    ElMessage.error('暂停任务失败')
    throw error
  }
}

/**
 * 恢复任务
 * @param id 任务ID
 */
export const resumeTask = async (id: number): Promise<void> => {
  try {
    await request.patch(`/api/tasks/${id}/resume`)
    ElMessage.success('任务已恢复')
  } catch (error) {
    ElMessage.error('恢复任务失败')
    throw error
  }
}

// 缓存最近请求的任务数据
const taskCache = new Map<number, Task>()

/**
 * 获取任务详情（带缓存）
 * @param id 任务ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 任务详情
 */
export const getTaskWithCache = async (id: number, forceRefresh = false): Promise<Task> => {
  if (!forceRefresh && taskCache.has(id)) {
    return taskCache.get(id)!
  }

  const task = await getTask(id)
  taskCache.set(id, task)
  return task
}
